package maliklund87.spiritrpg;

import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;

public class Game extends BasicGame implements LogicManager   {
	private LogicHandler currentLogic = null;
	private LogicHandler newLogic = null;
	private boolean logicChanged = false;

	public Game(String title) {
		super(title);
		currentLogic = new MainMenu(this);
	}

	@Override
	public void render(GameContainer gameContainer, Graphics graphics) throws SlickException {
		currentLogic.render(gameContainer, graphics);
	}

	@Override
	public void init(GameContainer gameContainer) throws SlickException {
		currentLogic.init(gameContainer);
	}

	@Override
	public void update(GameContainer gameContainer, int delta) throws SlickException {
		if (logicChanged){
			handleLogicChange(gameContainer);
		} else {
			currentLogic.update(gameContainer, delta);
		}
	}

	@Override
	public void setLogicHandler(LogicHandler newLogicHandler) {
		newLogic = newLogicHandler;
		logicChanged = true;
	}
	
	private void handleLogicChange(GameContainer gameContainer) throws SlickException{
		if (newLogic == null){
			gameContainer.exit();
		} else {
			currentLogic.exit();
			currentLogic = newLogic;
			init(gameContainer);
			newLogic = null;
			logicChanged = false;
		}
	}

}
